import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Product } from '@/api/product'
import { cartApi, type CartItem as ApiCartItem, type AddToCartRequest } from '@/api/cart'
import { ElMessage } from 'element-plus'

export interface CartItem {
  id: number
  userId: number
  productId: number
  quantity: number
  price: number
  selected: boolean
  createdAt: string
  updatedAt: string
  product?: Product
}

export const useCartStore = defineStore('cart', () => {
  // 状态
  const items = ref<CartItem[]>([])
  const loading = ref(false)

  // 计算属性
  const totalCount = computed(() => {
    return items.value.reduce((total, item) => total + item.quantity, 0)
  })

  const totalPrice = computed(() => {
    return items.value.reduce((total, item) => {
      const price = item.price || 0
      return total + price * item.quantity
    }, 0)
  })

  const selectedItems = computed(() => {
    return items.value.filter(item => item.selected)
  })

  const selectedTotalPrice = computed(() => {
    return selectedItems.value.reduce((total, item) => {
      const price = item.price || 0
      return total + price * item.quantity
    }, 0)
  })

  // 从本地存储加载购物车
  const loadCartFromStorage = () => {
    try {
      const savedCart = localStorage.getItem('cart')
      if (savedCart) {
        items.value = JSON.parse(savedCart)
      }
    } catch (error) {
      console.error('加载购物车失败:', error)
    }
  }

  // 保存购物车到本地存储
  const saveCartToStorage = () => {
    try {
      localStorage.setItem('cart', JSON.stringify(items.value))
    } catch (error) {
      console.error('保存购物车失败:', error)
    }
  }

  // 从服务器获取购物车
  const fetchCartItems = async () => {
    loading.value = true
    try {
      const response = await cartApi.getCartItems()
      items.value = response.data || []
      saveCartToStorage()
    } catch (error) {
      console.error('获取购物车失败:', error)
      // 如果网络请求失败，从本地存储加载
      loadCartFromStorage()
    } finally {
      loading.value = false
    }
  }

  // 添加商品到购物车
  const addToCart = async (product: Product, quantity = 1) => {
    try {
      const addRequest: AddToCartRequest = {
        productId: product.id,
        quantity
      }

      const response = await cartApi.addToCart(addRequest)
      
      // 重新获取购物车列表以保持同步
      await fetchCartItems()
      
      ElMessage.success('已添加到购物车')
      return { success: true, message: '已添加到购物车' }
    } catch (error: any) {
      console.error('添加到购物车失败:', error)
      const message = error.response?.data?.message || '添加失败'
      ElMessage.error(message)
      return { success: false, message }
    }
  }

  // 更新商品数量
  const updateQuantity = async (itemId: number, quantity: number) => {
    try {
      if (quantity <= 0) {
        return await removeItem(itemId)
      }
      
      await cartApi.updateCartItem(itemId, { quantity })
      await fetchCartItems()
      
      ElMessage.success('更新成功')
      return { success: true, message: '更新成功' }
    } catch (error: any) {
      console.error('更新数量失败:', error)
      const message = error.response?.data?.message || '更新失败'
      ElMessage.error(message)
      return { success: false, message }
    }
  }

  // 移除商品
  const removeItem = async (itemId: number) => {
    try {
      await cartApi.removeCartItem(itemId)
      await fetchCartItems()
      
      ElMessage.success('已移除')
      return { success: true, message: '已移除' }
    } catch (error: any) {
      console.error('移除商品失败:', error)
      const message = error.response?.data?.message || '移除失败'
      ElMessage.error(message)
      return { success: false, message }
    }
  }

  // 切换商品选中状态
  const toggleItemSelection = async (itemId: number) => {
    try {
      const item = items.value.find(item => item.id === itemId)
      if (item) {
        const newSelected = !item.selected
        await cartApi.updateCartItem(itemId, { selected: newSelected })
        await fetchCartItems()
      }
    } catch (error) {
      console.error('更新选中状态失败:', error)
    }
  }

  // 全选/取消全选
  const toggleAllSelection = async (selected: boolean) => {
    try {
      await cartApi.selectAll(selected)
      await fetchCartItems()
    } catch (error) {
      console.error('全选操作失败:', error)
    }
  }

  // 清空购物车
  const clearCart = async () => {
    try {
      await cartApi.clearCart()
      await fetchCartItems()
      
      ElMessage.success('购物车已清空')
      return { success: true, message: '购物车已清空' }
    } catch (error: any) {
      console.error('清空购物车失败:', error)
      const message = error.response?.data?.message || '清空失败'
      ElMessage.error(message)
      return { success: false, message }
    }
  }

  // 获取商品在购物车中的数量
  const getItemQuantity = (productId: number) => {
    const item = items.value.find(item => item.productId === productId)
    return item ? item.quantity : 0
  }

  // 检查商品是否在购物车中
  const isInCart = (productId: number) => {
    return getItemQuantity(productId) > 0
  }

  // 初始化购物车
  const initCart = async () => {
    loadCartFromStorage()
    const token = localStorage.getItem('token')
    if (token) {
      await fetchCartItems()
    }
  }

  return {
    // 状态
    items,
    loading,
    
    // 计算属性
    totalCount,
    totalPrice,
    selectedItems,
    selectedTotalPrice,
    
    // 方法
    fetchCartItems,
    addToCart,
    updateQuantity,
    removeItem,
    toggleItemSelection,
    toggleAllSelection,
    clearCart,
    getItemQuantity,
    isInCart,
    initCart,
  }
})